import StandModal from '@/components/StandModal';
import utils from '@/utils';
import Taro, { useRouter } from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';

const CodeState = {
  1201: '宝贝被抢空了，快去逛逛别的吧~',
};

function transform({ code, message, exceptionType }) {
  let cancelText;
  let content;

  if (exceptionType === 1) {
    cancelText = undefined;
    content = '您购买的部分商品无库存';
  } else if (exceptionType === 2) {
    cancelText = undefined;
    content = '您选择的优惠券/积分/礼品卡不可用，请重新选择';
  } else {
    content = CodeState[code] ?? message ?? '订单失效';
    cancelText = '去购物车';
  }

  return {
    cancelText,
    content,
  };
}

const OrderFailedDialog = ({
  dispatch,
  status: { isOpened, code, message, content: { exceptionType } = {} },
  onClose,
  onCancel,
  onConfirm,
}) => {
  const { path, params: routerParams } = useRouter();

  const [realOpened, setRealOpened] = useState(isOpened);

  // 当外部变量变更时, 更新内部状态
  useEffect(() => {
    if (isOpened !== realOpened && message) {
      setRealOpened(isOpened);
    }
  }, [isOpened]);

  // 去购物车
  const handleCancel = () => {
    if (onCancel) {
      return onCancel();
    }
    setRealOpened(false);

    const u = utils.getCartPagePath();

    if (Taro.$isH5) {
      Taro.redirectTo({url:u});
    } else {
      utils.goCartPage(dispatch, 'switchTab');
    }
  };

  const handleClose = () => {
    if (onClose) {
      onClose();
    }
  };

  const handleConfirm = () => {
    if (onConfirm) {
      onConfirm();
      return;
    }

    setRealOpened(false);

    // 1 有某个商品无库存 2 券/积分/礼品卡状态异常
    if (exceptionType === 1) {
      reloadPage();
    } else if (exceptionType === 2) {
      reloadPage();
    } else {
      Taro.navigateBack();
    }
  };

  const reloadPage = () => {
    let url =
      path +
      '?' +
      Object.keys(routerParams)
        .filter((key) => {
          return key !== '__key_';
        })
        .map((key) => {
          return `${key}=${routerParams[key]}`;
        })
        .join('&');

    Taro.redirectTo({ url });
  };

  return (
    <StandModal
      {...{
        isOpened: realOpened,

        confirmText: '确定',
        onClose: handleClose,
        onCancel: handleCancel,
        onConfirm: handleConfirm,

        ...transform({ code, message, exceptionType }),

        closeOnClickOverlay: false,
      }}
    />
  );
};

export default connect(({}) => ({}))(OrderFailedDialog);
